package com.zhangmeng.online.exam.service.impl;

import com.zhangmeng.jwt.dto.LoginUser;

import com.zhangmeng.online.exam.entity.Permission;
import com.zhangmeng.online.exam.entity.User;
import com.zhangmeng.online.exam.service.PermissionService;
import com.zhangmeng.online.exam.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;


/**
 * @author zm
 * @date 2025/3/22 15:42
 * @version: 1.0
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private PermissionService permissionService;

    @Override
    public org.springframework.security.core.userdetails.UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = this.userService.loadUserByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户未找到");
        }

        //判断用户状态是否正常
        if (!user.getDeleteStatus()) {
            if (user.getStatus().equals(User.Status.LOCKED)) {
                throw new LockedException("用户被锁定,请联系管理员");
            }
            if (user.getStatus().equals(User.Status.DISABLED)) {
                throw new DisabledException("用户已作废");
            }
        }
        //根据用户查询权限列表
        List<Permission> permissions = this.permissionService.findByUserId(user.getId());
        return new LoginUser(user.getId(),username,user.getPassword(),this.convert_permissions(permissions));
    }

    //转换
    private List<com.zhangmeng.jwt.dto.Permission> convert_permissions (List<Permission> permissions){
        return permissions.parallelStream().filter(permission -> !StringUtils.isEmpty(permission.getName()))
                .map(permission -> {
                    com.zhangmeng.jwt.dto.Permission permission1 = new com.zhangmeng.jwt.dto.Permission();
                    permission1.setTitle(permission.getName());
                    return   permission1;
                }).collect(Collectors.toList());
    }
}
